package com.coszero.utils.device

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.telephony.TelephonyManager
import android.widget.Toast
import com.coszero.utils.R
import com.coszero.utils.utils.LogX

/**
 * @author xmqian
 * @date 2018/1/15 0015
 * @link(https://blog.csdn.net/lxping51/article/details/70145322)
 * @desc 网络监听, 及网络状态获取, 以下是涉及的权限
 * <uses-permission android:name="android.permission.INTERNET"></uses-permission>
 * <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
 * <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
 * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
 * @version 1
 */
object DeviceNetStateUtils {
    var TAG: String = "DeviceNetStateUtils"
    private var showToast: Boolean = false

    /*是否注册wifi监听*/
    private var isRegWifi: Boolean = false

    /**
     * 是否内部对网络状态进行提示
     *
     * @param showToast
     */
    fun setShowToast(showToast: Boolean) {
        DeviceNetStateUtils.showToast = showToast
    }

    /**
     * 是否注册wifi监听
     *
     * @param isRegWifi
     */
    fun setIsRegWifi(isRegWifi: Boolean) {
        DeviceNetStateUtils.isRegWifi = isRegWifi
    }

    private var netStateBroadcastReceiver: NetStateBroadcastReceiver? = null

    var wifiStateReceiver: BroadcastReceiver? = null

    private fun registerWifiReceiver(context: Context) {
        wifiStateReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val s: Int = getWifiState(context)
                val toast: Int
                if (s < -50) {
                    toast = R.string.ut_toast_wifi_signal_weak
                } else {
                    toast = R.string.ut_toast_wifi_signal_good
                }
                LogX.d("#### wifi网络状态监听：" + toast)
                if (showToast) {
                    Toast.makeText(context, toast, Toast.LENGTH_SHORT).show()
                }
            }
        }
        context.registerReceiver(wifiStateReceiver, IntentFilter(WifiManager.RSSI_CHANGED_ACTION))
    }

    fun registerNetState(context: Context, netChangeListener: NetChangeListener?) {
        registerNetState(context, false, netChangeListener)
    }

    /**
     * 注册网络变化监听
     *
     * @param context
     * @param netChangeListener
     * @param isRegWifi 是否注册wifi强度监听
     */
    fun registerNetState(
        context: Context,
        isRegWifi: Boolean,
        netChangeListener: NetChangeListener?
    ) {
        setIsRegWifi(isRegWifi)
        if (netStateBroadcastReceiver == null) {
            netStateBroadcastReceiver = NetStateBroadcastReceiver()
        }
        netStateBroadcastReceiver!!.addListener(netChangeListener)
        val filter: IntentFilter = IntentFilter()
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        context.registerReceiver(netStateBroadcastReceiver, filter)
        LogX.d(TAG, "注册网络监听")
        //是wifi的情况下，注册wifi信号监听
        if (getCurrentNetType(context) == NetState.WIFI.type && isRegWifi) {
            LogX.d(TAG, "注册wifi网络监听")
            registerWifiReceiver(context)
        }
    }

    /**
     * 取消注册网络变化监听
     *
     * @param context
     */
    fun unregisterNetState(context: Context) {
        LogX.d(TAG, "取消网络监听")
        if (netStateBroadcastReceiver != null) {
            context.unregisterReceiver(netStateBroadcastReceiver)
        }
        if (wifiStateReceiver != null && isRegWifi) {
            LogX.d(TAG, "取消wifi网络监听")
            context.unregisterReceiver(wifiStateReceiver)
            wifiStateReceiver = null
        }
    }

    /**
     * 获取当前的网络状态
     *
     * @param context
     * @return
     */
    fun getCurrentNetType(context: Context): String {
        // String type = "unknown";
        var state: Int = NetState.UNKOWN.state
        var type: String = NetState.UNKOWN.type
        val cm: ConnectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val info: NetworkInfo? = cm.getActiveNetworkInfo()

        if (info == null) {
            // type = "unknown";
            state = NetState.UNKOWN.state
        } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            // type = "wifi";
            state = NetState.WIFI.state
        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            val subType: Int = info.getSubtype()
            if (subType == TelephonyManager.NETWORK_TYPE_CDMA || subType == TelephonyManager.NETWORK_TYPE_GPRS || subType == TelephonyManager.NETWORK_TYPE_EDGE) {
                // type = "2g";
                state = NetState.CDMA.state
            } else if (subType == TelephonyManager.NETWORK_TYPE_UMTS || subType == TelephonyManager.NETWORK_TYPE_HSDPA || subType == TelephonyManager.NETWORK_TYPE_EVDO_A || subType == TelephonyManager.NETWORK_TYPE_EVDO_0 || subType == TelephonyManager.NETWORK_TYPE_EVDO_B) {
                // type = "3g";
                state = NetState.UMTS.state
            } else { // LTE是3g到4g的过渡，是3.9G的全球标准 if (subType ==
                // TelephonyManager.NETWORK_TYPE_LTE)
                // type = "4g";
                state = NetState.LTE.state
            }
        }
        when (state) {
            1 -> type = NetState.WIFI.type
            2 -> type = NetState.CDMA.type
            3 -> type = NetState.UMTS.type
            4 -> type = NetState.LTE.type
            5 -> type = NetState.UNKOWN.type
            else -> type = NetState.UNKOWN.type
        }
        return type
    }

    /**
     * 获取WiFi的信号强度
     * 这里得到信号强度就靠wifiinfo.getRssi()这个方法。
     * 得到的值是一个0到-100的区间值，是一个int型数据，
     * 其中0到-50表示信号最好，-50到-70表示信号偏差，
     * 小于-70表示最差，有可能连接不上或者掉线，一般Wifi已断则值为-200
     *
     * @param context
     * @return
     */
    fun getWifiState(context: Context): Int {
        val wifi_service: WifiManager =
            context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo: WifiInfo = wifi_service.getConnectionInfo()
        val rssi: Int = wifiInfo.getRssi()
        //        String s = String.valueOf(rssi) + "dBm";
        return rssi
    }

    /**
     * 判断当前网络是否为wifi
     *
     * @param mContext
     * @return 是：true;不是：false
     */
    fun isWifi(mContext: Context): Boolean {
        if (getCurrentNetType(mContext) == NetState.WIFI.type) {
            return true
        }
        return false
    }

    /**
     * 判断网络是否可用
     *
     * @param context context
     * @return 可用：true,不可用：false
     */
    @JvmStatic
    fun isNetWorkAvailble(context: Context): Boolean {
        try {
            val connectivity: ConnectivityManager? = context
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
            if (connectivity != null) {
                val info: NetworkInfo? = connectivity.getActiveNetworkInfo()
                if ((info != null) && (info.isConnected())) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }

        return false
    }

    /**
     * 网络状态类型
     */
    internal enum class NetState(val type: String, val state: Int) {
        WIFI("wifi", 1), CDMA("2G", 2), UMTS("3G", 3), LTE("4G", 4), UNKOWN("unkonw", 5)
    }


    /**
     * 网络变化广播接收器
     */
    class NetStateBroadcastReceiver : BroadcastReceiver() {
        private var netChangeListener: NetChangeListener? = null

        override fun onReceive(context: Context, intent: Intent) {
            if (intent.getAction() == ConnectivityManager.CONNECTIVITY_ACTION) {
                val netWorkState: String = getCurrentNetType(context)
                if (netChangeListener != null) {
                    netChangeListener!!.onNetStateChange(netWorkState)
                }
            }
        }

        fun addListener(netChangeListener: NetChangeListener?) {
            this.netChangeListener = netChangeListener
        }
    }

    /**
     * 网络切换接口
     */
    interface NetChangeListener {
        fun onNetStateChange(netWorkState: String?)
    }
}
